package base;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author: DRevelation
 * @Date: 2021/4/8 16:11
 */
public class ThreadLocalDemo {

    static ThreadLocal<String> localVar = new ThreadLocal<>();
    static ThreadLocal<String> localVar2 = new ThreadLocal<>();

    public static void main(String[] args) {
        ExecutorService exec = Executors.newSingleThreadExecutor();
        for (int i = 0; i < 1; i++) {
            int finalI = i;
            exec.execute(() -> {
                //多次赋值会覆盖，用2个ThreadLocal可以存储多个对象
                localVar.set("exe-" + finalI);
                localVar2.set("exe2-" + finalI);
                print("thread-" + finalI);
                print("after remove-" + localVar.get());
            });
        }
    }

    static void print(String str) {
        System.out.println(str + ": " + localVar.get());
        System.out.println(str + ": " + localVar2.get());
        localVar.remove();
    }

}
